<template>
  <div>
    <hm-header>登录</hm-header>
    <hm-logo></hm-logo>
    <!-- 输入框 -->
    <van-cell-group>
      <van-field
        label="用户名"
        placeholder="请输入用户名"
        v-model="username"
        @input="checkPhone1"
        @clear="clearPhone1"
        clearable
        :error-message="usernameErrMsg"
      />
      <van-field
        label="手机号"
        placeholder="请输入密码"
        v-model="password"
        @input="checkPhone2"
        @clear="clearPhone2"
        clearable
        :error-message="passwordErrMsg"
      />
    </van-cell-group>
    <!-- 按钮 -->
    <hm-button @click.native="startLogin">登录</hm-button>
    <!-- 跳转到注册页面 -->
    <div class="go-register">
      没有账号?
      <router-link class="link" to="/register">注册</router-link>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 用户名
      username: '10086',
      usernameErrMsg: '',
      // 密码
      password: '123',
      passwordErrMsg: ''
    }
  },
  methods: {
    // 校验1
    checkPhone1() {
      let reg = /^\d{1,5}$/
      if (reg.test(this.username)) {
        this.usernameErrMsg = ''
      } else {
        this.usernameErrMsg = '用户名格式不正确'
      }
    },
    clearPhone1() {
      this.username = ''
      this.usernameErrMsg = ''
    },
    clearPhone2() {
      this.passwordErrMsg = ''
      this.password = ''
    },
    // 校验2
    checkPhone2() {
      let reg = /^\d{1,3}$/
      if (reg.test(this.password.trim())) {
        this.passwordErrMsg = ''
      } else {
        this.passwordErrMsg = '密码格式不正确'
      }
    },
    startLogin() {
      if (
        this.usernameErrMsg === '' &&
        this.passwordErrMsg === '' &&
        this.username !== '' &&
        this.password !== ''
      ) {
        this.$axios
          .post('/login', {
            username: this.username,
            password: this.password
          })
          .then(res => {
            const { statusCode, data } = res.data
            if (statusCode === 200) {
              this.$toast.success('登录成功')

              localStorage.setItem('token', data.token)
              localStorage.setItem('user_id', data.user.id)
              console.log(11)

              this.$router.push('/user')
            } else {
              this.$toast.fail('登录失败')
            }
          })
      } else {
        console.log('错误')
        this.$toast.fail('校验失败')
      }
    }
  },
  created() {
    console.log(this.$route)
    const { password, username } = this.$route.params
    if (password && username) {
      this.password = password
      this.username = username
    }
  }
}
</script>

<style scoped lang="less">
.go-register {
  padding: 0 20px;
  font-size: 18px;
  text-align: right;

  .link {
    color: green;
  }
}
</style>
